<?php
/**
 * Main Frontend controller for Forms Component
 *
 * @version		$Id: controller.php 142 2009-04-27 16:25:55Z dr_drsh $
 * @package		Joomla
 * @subpackage	JForms
 * @copyright	Copyright (C) 2008 Mostafa Muhammad. All rights reserved.
 * @license		GNU/GPL
 */

jimport('joomla.application.component.controller');

/**
 * Main Frontend Controller
 *
 * @package    Joomla
 * @subpackage JForms
 */
class FrontendController extends JController {

    /**
     * constructor (registers additional tasks to methods)
     *
     * @return void
     */
    function __construct() {
        parent::__construct();

        // Register Extra tasks
        $this->registerTask( 'form'  , 'form');
        $this->registerTask( 'thank' , 'thank');
        $this->registerTask( 'save'  , 'save');
        $this->registerTask( 'validate'  , 'validate');

    }


    /**
     * Validates record and stores it
     *
     * @access	public
     */
    function save() {
        JRequest::checkToken('post') or jexit( 'Invalid Token' );

        //Load element plugins
        global $JFormGlobals;
        $pManager =& $JFormGlobals['JFormsPlugin'];
        $pManager->loadElementPlugins();
        $pManager->loadStoragePlugins();

        $id     = JRequest::getInt( 'id' );
        $itemid = JRequest::getInt( 'Itemid' );

        $model  = & $this->getModel('form');
        $form    = $model->getForm( $id );

        if( $form == null ) {
            JError::raiseError( 404, JText::_("Page not found") );
        }

        //Check premissions
        $user   =& JFactory::getUser();
        $allowedGroups = explode(',', $form->groups);
        if( !in_array( $user->gid, $allowedGroups ) ) {
            JError::raiseError( 403, JText::_("Access Forbidden") );
        }

        //If Profile mode form, Allow only registered users
        if( !$user->id && $form->type == JFORMS_TYPE_PROFILE ) {
            JError::raiseError( 403, JText::_("Access Forbidden") );
        }

        //The record data
        $postVars = JRequest::get('post');


        $mapper = new VA_Form_Form_Mapper_XML();
        $jForm = VA_Form_Form::fromXML($form->xmlDescription)
                ->setGID($form->storagePluginParameters['Database']['tableName']);
        $jForm->bind($postVars[$jForm->getPrefix()],
                empty($_FILES[$jForm->getPrefix()])?array():VA_Form_Form::prepareFiles($_FILES[$jForm->getPrefix()])
        );
        /*
        *	Validation errors
        */
        if( $jForm->isValid() === FALSE ) {
            //There has been a validation error, return to previous page and save error data in session
            if(array_key_exists( 'from_jforms_plugin', $postVars ) &&
                    intval($postVars['from_jforms_plugin'])) {

                //Use session to store form previous State
                $formStateInfo = array();
                for($i=0;$i<count($form->fields);$i++ ) {
                    $formStateInfo[$form->fields[$i]->parameters['hash']] =
                            array(
                            $form->fields[$i]->validationError,
                            $form->fields[$i]->defaultValue
                    );
                }
                $document   =& JFactory::getDocument();
                $_SESSION['JFormsSession']['FormState'][$form->id] = $formStateInfo;

                $uri = $postVars['url'];

                //Appends frmReturn=1 to the request URL to inform the plugin that we're returning form vaildation
                $jrouter =& JRouter::getInstance('site');
                $juri    =& JURI::getInstance( $uri );

                if( !$juri->isInternal( $uri ) ) {
                    die('Hacking attempt');
                }
                $urlFragments    = $jrouter->parse($juri);
                if( !array_key_exists( 'frmReturn', $urlFragments ))
                    $urlFragments['frmReturn'] = '1';

                $redirectURL = 'index.php?';
                foreach( $urlFragments as $key => $value ) {
                    $redirectURL .= $key.'='.$value.'&';
                }
                $redirectURL =  JRoute::_($redirectURL, false);

                $this->setRedirect( $redirectURL );


            } else {

                //Running from com_electroforms context
                if(
                !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.'tmpl'.DS.$form->theme.'.php') ||
                        !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.'tmpl'.DS.$form->theme.'_thank.php') ||
                        !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.$form->theme.'.css')
                )$form->theme = 'default';

                $document   =& JFactory::getDocument();
                $viewType	= $document->getType();
                $viewName	= 'form';
                $viewLayout	= $form->theme;

                $view = & $this->getView( $viewName, $viewType, '', array( 'base_path'=>$this->_basePath));

                // Set the layout
                $view->setLayout($viewLayout);

                // Display the view
                $view->display($form, $jForm);

            }
        } else {
            //Everything went okay?
            //Clear session Form states
            unset($_SESSION['JFormsSession']);

            $response = $pManager->invokeMethod('getNextInsertID',
                    JFORM_PLUGIN_STORAGE,
                    array('Database'),
                    array( $form ) );
            $nextInsertId = intval( $response['Database'] );

            $elements = $jForm->getAssocValues();
            //inject needeed parameters to be saved in old way
            foreach($postVars[$jForm->getPrefix()] as $key => $value) {
                
                if(!is_scalar($value) && array_key_exists($key, $elements)) {
                    if( $elements[$key] instanceof VA_Form_FormElement_WithChoice) {
                        $value = $elements[$key]->getSelectedTitles();
                    } elseif(is_array($value)) $value = join(' ', $value);
                }
                $postVars[$key] = $value;
            }
            unset($postVars[$jForm->getPrefix()]);

            $model->save($form, $postVars, $jForm);
            /* @var $db JDatabaseMySQL */
            $db = JFactory::getDBO();
            $jForm->postEvent();

            $uri = JRoute::_( 'index.php?option=com_electroforms&task=thank&id='.$form->id.'&Itemid='.$itemid, false );
            $this->setRedirect( $uri );
        }

    }

    /**
     * Displays the thank you page
     *
     * @access	public
     */
    function thank() {
        $id	= JRequest::getInt( 'id' );

        $document =& JFactory::getDocument();


        $model  = & $this->getModel('form');
        $data   = $model->getThankMessage( $id );

        if( is_null( $data ) ) {
            JError::raiseError( 404, JText::_("Page not found") );
        }


        if(
        !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.'tmpl'.DS.$data->theme.'.php') ||
                !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.'tmpl'.DS.$data->theme.'_thank.php') ||
                !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.$data->theme.'.css')
        )$data->theme = 'default';

        $viewType	= $document->getType();
        $viewName	= 'form';
        $viewLayout	= $data->theme.'_thank';
        $view = & $this->getView( $viewName, $viewType, '', array( 'base_path'=>$this->_basePath));
        // Set the layout
        $view->setLayout($viewLayout);
        // Display the view
        $view->display_thank( $data );
    }

    /**
     * Method to display the view,  (Currently it is a faithful copy from the base)
     *
     * @access	public
     */
    function display() {
        jimport('joomla.filesystem.file');

        $document =& JFactory::getDocument();
        $id	= JRequest::getInt( 'id' );

        $model = & $this->getModel('form');
        $form  = $model->getForm( $id );

        if( $form == null ) {
            JError::raiseError( 404, JText::_("Page not found") );
        }

        //Check premissions
        $user   =& JFactory::getUser();
        $allowedGroups = explode(',', $form->groups);
        if( !in_array( $user->gid, $allowedGroups ) ) {
            JError::raiseError( 403, JText::_("Access Forbidden") );
        }

        //If Profile mode form, Allow only non-guests
        if( !$user->id && $form->type == JFORMS_TYPE_PROFILE ) {
            JError::raiseError( 403, JText::_("Access Forbidden") );
        }


        //Sort elements
        $sortedElements = array();
        foreach( $form->fields as $f ) {
            $sortedElements[$f->position] = $f;
        }
        $form->fields = $sortedElements;

        //Load previously stored Data
        if( $user->id && $form->type == JFORMS_TYPE_PROFILE ) {
            $record = $model->getRecordByUid( $form, $user->id );
            if( count($record) ) {
                foreach( $form->fields as $key => $value ) {
                    //Fix for PHP4 since foreach doesn't return references.
                    $f = &$form->fields[$key];
                    if( array_key_exists( $f->parameters['hash'], $record  ))
                        $f->parameters['defaultValue'] = $record[$f->parameters['hash']];
                }
            }
        }
        //Check the selected theme, if any file is missing, load default

        if(
        !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.'tmpl'.DS.$form->theme.'.php') ||
                !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.'tmpl'.DS.$form->theme.'_thank.php') ||
                !JFile::exists( JFORMS_FRONTEND_PATH.DS.'views'.DS.'form'.DS.$form->theme.'.css')
        )$form->theme = 'default';

        $mapper = new VA_Form_Form_Mapper_XML();

        $JForm = $mapper->FromSource($form->xmlDescription)
                ->setGID($form->storagePluginParameters['Database']['tableName']);
        
        $viewType	= $document->getType();
        $viewName	= $form->view;
        $viewLayout	= $form->theme;

        $view = & $this->getView( $viewName, $viewType, '', array( 'base_path'=>$this->_basePath));

        // Set the layout
        $view->setLayout($viewLayout);

        // Display the view
        $view->display($form, $JForm);
    }

    private function isAjaxRequest() {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
                        &&
                        ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
    }


    public function validate_remote() {
        if(TRUE || $this->isAjaxRequest()) {
            $return = TRUE;
            echo json_encode($return);
        }
        exit;
    }

    /**
     * используется для валидации через Ajax
     *
     */
    public function validate() {
        header('Content-Type: application/json');
        if($this->isAjaxRequest()) {
            $return = FALSE;
            $name	= JRequest::getString('name');
            $query = <<<QUERY
 SELECT ff.xmlDescription AS form_id FROM #__jforms_parameters fp
   INNER JOIN #__jforms_forms ff
   ON fp.fid = ff.id
   WHERE fp.parameter_name="tableName"
   AND fp.parameter_value=%s
QUERY;
            /* @var $db JDatabaseMySQL */
            $db = JFactory::getDBO();
            $query = sprintf($query, $db->Quote($name));
            $db->setQuery($query);
            $res = $db->query();
            $result = $db->loadResultArray();
            if(count($result) > 0) {
                $mapper = new VA_Form_Form_Mapper_XML();
                $form = $mapper->FromSource($result[0]);
                $form->bind($_GET['jform_'.$name]);
                if( $form->isPartialValid()) $return = TRUE;
                else $return = FALSE;//$form->getErrors();
            }
            echo json_encode($return);
        }
        exit;
    }
}

